package Utils

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cast"
	"strings"
)

//map占位符替换
func MapPlaceHolder(sourceStr string, targetMap map[string]interface{}) (string, error) {

	sourceMap := make(map[string]interface{})
	err := json.Unmarshal([]byte(sourceStr), &sourceMap)
	if err != nil {
		fmt.Println("err")
		return "", err
	}

	for k, v := range sourceMap {
		switch v.(type) {
		case string:
			placeStr := ""
			if strings.Contains(v.(string), "#") {
				vSplit := strings.Split(v.(string), "#")
				if len(vSplit)%2 == 0 {
					continue
				}
				for i := 0; i < len(vSplit); i++ {
					if i%2 == 0 {
						placeStr += vSplit[i]
					} else {
						value, ok := targetMap[vSplit[i]]
						if ok {
							placeStr += cast.ToString(value)
						}
					}
				}
				sourceMap[k] = placeStr
			}
		default:
		}
	}

	d, err := json.Marshal(sourceMap)
	if err != nil {
		return "", err
	}
	return string(d), nil
}
